package com.sx.gongzhong.activity;


import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;

import com.sx.gongzhong.BaseActivity;
import com.sx.gongzhong.MyApplication;
import com.sx.gongzhong.R;
import com.sx.gongzhong.model.MsgEvent;
import com.sx.gongzhong.model.UserInfoBean;
import com.sx.gongzhong.net.MyRxBus;
import com.sx.gongzhong.net.ServiceFactory;
import com.sx.gongzhong.pest.LoginPest;
import com.sx.gongzhong.utils.ToastUtils;
import com.sx.gongzhong.view.LoginView;
import com.sx.gongzhong.widget.ClearEditText;
import com.sx.gongzhong.widget.LoadDialog;
import com.sx.gongzhong.widget.MyPopupWindow;

import java.util.HashSet;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

public class LoginActivity extends BaseActivity implements LoginView {

    @BindView(R.id.username_edit)
    ClearEditText etName;
    @BindView(R.id.password_edit)
    ClearEditText etPwd;
    @BindView(R.id.cb_rememberPwd)
    CheckBox cb_rememberPwd;
    private EditText etIp,etPort;
    private MyPopupWindow popupWindow;
    private IDataStorage dataStorage;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        setGoneTitle();
        initView();
    }

    private void initView() {
        dataStorage = DataStorageFactory.getInstance(
                getApplicationContext(),
                DataStorageFactory.TYPE_DATABASE);
        if (dataStorage.contains(UserInfoBean.class,getPackageName())){
            UserInfoBean userBean = dataStorage.load(UserInfoBean.class,getPackageName());
            if (userBean.isCheck){
                etName.setText(userBean.loginName);
                etPwd.setText(userBean.password);
                cb_rememberPwd.setChecked(userBean.isCheck);
            }
        }
    }

    @OnClick({R.id.login_btn,R.id.tv_SetIP,R.id.tv_Cancel,R.id.tv_Register,R.id.tv_ForgetPwd})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.login_btn:
                loginStart();
                break;
            case R.id.tv_SetIP:
                createPopupWindow();
                break;
            case R.id.tv_Cancel:
                finish();
                break;
            case R.id.tv_Register:
               startActivityForResult(new Intent(this,RegisterActivity.class),100);
                break;
            case R.id.tv_ForgetPwd:
                startActivity(new Intent(this,ForgetPwdActivity.class));
                break;
        }
    }

    /**
     * 提交登录
     */
    private void loginStart() {
        String name = etName.getText().toString().trim();
        if (TextUtils.isEmpty(name)){
            ToastUtils.showToast(this,"请输入姓名");
            return;
        }
        String password = etPwd.getText().toString().trim();
        if (TextUtils.isEmpty(password)){
            ToastUtils.showToast(this,"请输入密码");
            return;
        }
        LoadDialog.show(this,"登录中...");
        new LoginPest(this).login(this,name,password);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 100:
                    if (data!=null){
                        etName.setText(data.getStringExtra("UserName"));
                        etPwd.setText("");
                    }
                    break;
            }
        }
    }

    public void createPopupWindow() {
        if (popupWindow == null) {
            View view = LayoutInflater.from(this).inflate(R.layout.pop_set_ip, null);
            etIp = (EditText) view.findViewById(R.id.etIP);
            etPort=(EditText) view.findViewById(R.id.etPort);
            popupWindow = new MyPopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT, true);
            popupWindow.setTouchable(true);
            popupWindow.setOutsideTouchable(false);
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.alpha(128)));
            view.findViewById(R.id.bt_Cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });
            view.findViewById(R.id.bt_Set).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setIp();
                    popupWindow.dismiss();
                }
            });
        }

        popupWindow.showAtLocation(etName, Gravity.CENTER,0,0);
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(LoginActivity.this);
        ToastUtils.showToast(LoginActivity.this,message);
    }

    @Override
    public void loginSuccess(UserInfoBean userBean) {
        LoadDialog.dismiss(LoginActivity.this);
        ToastUtils.showToast(LoginActivity.this,"登录成功");
        JPushInterface.resumePush(getApplicationContext());
        JPushInterface.setAlias(this,0,userBean.id);
        userBean.password = etPwd.getText().toString().trim();
        userBean.isCheck = cb_rememberPwd.isChecked();
        MyApplication.instance.userBean=userBean;
        if (dataStorage.contains(UserInfoBean.class,getPackageName())){
            UserInfoBean saveUser = dataStorage.load(UserInfoBean.class,getPackageName());
//            if (saveUser.getId().equals(userBean.getId())){
//                userBean.setJuPush(saveUser.isJuPush());
//            }else {
//                userBean.setJuPush(true);
//            }
        }
//        if (userBean.isJuPush()){
//            JPushInterface.resumePush(getApplicationContext());
//        }else {
//            JPushInterface.stopPush(getApplicationContext());
//        }
        dataStorage.storeOrUpdate(userBean,getPackageName());
        MyRxBus.get().post(new MsgEvent("MyFragment",2,userBean));
        MyRxBus.get().post(new MsgEvent<>("MessageFragment",1,"收到消息"));
        MyRxBus.get().post(new MsgEvent("CommentListAdapter",1,null));
//        startActivity(new Intent(LoginActivity.this,MainActivity.class));
        finish();
    }
//    private void setJPushAlai(String id, UserBean.OrgBean org) {
//        JPushInterface.setAlias(this,0,id);
//        if (org != null){
//            Set<String> sets = new HashSet<>();
//            sets.add(org.getId());
//            JPushInterface.setTags(this,0,sets);
//        }
//    }
    /**
     * 设置ip
     */
    private void setIp() {
        String ip=etIp.getText().toString().trim();
        String port=etPort.getText().toString().trim();
        if (!TextUtils.isEmpty(ip)){
            ServiceFactory.OLD_API_BASE_URL="http://"+ip;
        }
        if (!TextUtils.isEmpty(port)){
            ServiceFactory.OLD_API_BASE_URL= ServiceFactory.OLD_API_BASE_URL+":"+port;
        }
    }

    @Override
    protected void onDestroy() {
        if (dataStorage != null){
            dataStorage = null;
        }
        super.onDestroy();
    }
}
